# -*- coding: utf-8 -*-  
# 1.no system is safe 2.If you dare to do it, you can win. 3.Enjoyment in the virtual world as well as in the real world
# python 3.6.3, create time is 2019/1/25 8:33 GMT+8
from socket import socket
from threading import Thread
from zlib import compress
from mss import mss

WIDTH = int(1366 / 1)
HEIGHT = int(768 / 1)


def send_screenshot(conn):
    with mss() as sct:
        rect = {
            'top': 0,
            'left': 0,
            'width': WIDTH,
            'height': HEIGHT
        }

        while 'recording':
            img = sct.grab(rect)
            pixels = compress(img.bgra, 1)
            size = len(pixels)
            size_len = (size.bit_length() + 7) // 8
            conn.send(bytes([size_len]))
            size_bytes = size.to_bytes(size_len, 'big')
            conn.send(size_bytes)
            conn.sendall(pixels)


def main(host='127.0.0.1', port=5000):
    sock = socket()
    sock.bind((host, port))
    try:
        sock.listen(5)
        print('服务器OK了')
        while 'connected':
            conn, addr = sock.accept()
            print('客户端连接ip为：', addr)
            thread = Thread(target=send_screenshot, args=(conn, ))
            thread.start()
    finally:
        sock.close()


if __name__ == '__main__':
    main()
